package dbext

// 字段对比器 对比俩个表的数据结构
type ColumnComparator struct {
	AddColumns    []Column
	ModifyColumns []Column
	DropColumns   []Column
}

// originalTable 原表
// dstTable 待修改的表
func (cc *ColumnComparator) Compare(originalTable string, originalConnection string, dstTable string, dstConnection string) *ColumnComparator {
	cc.Clear()
	originalColumns := NewTableInfoGetter(originalConnection).GetColumns(originalTable)
	dstColumns := NewTableInfoGetter(dstConnection).GetColumns(dstTable)
	// 获取待修改字段
	for _, dstColumn := range dstColumns {
		for _, originalColumn := range originalColumns {
			if dstColumn.Field == originalColumn.Field {
				if dstColumn.Type != originalColumn.Type ||
					dstColumn.Null != originalColumn.Null ||
					dstColumn.Default != originalColumn.Default ||
					dstColumn.Comment != originalColumn.Comment {
					modifyColumn := originalColumn
					modifyColumn.Table = dstTable
					cc.ModifyColumns = append(append(cc.ModifyColumns, modifyColumn))
				}
				break
			}
		}
	}

	// 获取待删除字段
	for _, dstColumn := range dstColumns {
		isDelete := true
		for _, originalColumn := range originalColumns {
			if dstColumn.Field == originalColumn.Field {
				isDelete = false
				break
			}
		}
		if isDelete {
			cc.DropColumns = append(cc.DropColumns, dstColumn)
		}
	}

	// 获取待新增字段
	for _, originalColumn := range originalColumns {
		isAdd := true
		for _, dstColumn := range dstColumns {
			if dstColumn.Field == originalColumn.Field {
				isAdd = false
				break
			}
		}
		if isAdd {
			addColumn := originalColumn
			addColumn.Table = dstTable
			cc.AddColumns = append(cc.AddColumns, addColumn)
		}
	}
	return cc
}

func (cc *ColumnComparator) ToDDLString() []string {
	var DDLSlice []string
	for _, modifyColumn := range cc.ModifyColumns {
		DDLSlice = append(DDLSlice, modifyColumn.ToModifyDDL())
	}
	for _, dropColumn := range cc.DropColumns {
		DDLSlice = append(DDLSlice, dropColumn.ToDropDDL())
	}
	for _, addC := range cc.AddColumns {
		DDLSlice = append(DDLSlice, addC.ToAddDDL())
	}
	return DDLSlice
}

func (cc *ColumnComparator) Clear() {
	cc.ModifyColumns = []Column{}
	cc.AddColumns = []Column{}
	cc.DropColumns = []Column{}
}
